package com.glela.goods.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import com.glela.goods.model.DistributaryTemplate;
import com.glela.goods.model.DistributaryTemplateDetails;
import com.glela.goods.model.Goods;
import com.glela.goods.model.GoodsNavigate;
import com.glela.goods.model.GoodsPrice;
import com.glela.goods.model.vo.goods.GoodsListResponse;
import com.glela.goods.service.DistributaryService;
import com.glela.goods.service.GoodsService;
import com.glela.goods.service.InventoryService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.mapper.GivePromotionHistoryMapper;
import com.glela.platform.mapper.GivePromotionListMapper;
import com.glela.platform.mapper.PromotionDetailMapper;
import com.glela.platform.mapper.UserMapper;
import com.glela.platform.mapper.UserPromotionMapper;
import com.glela.platform.model.GivePromotionHistory;
import com.glela.platform.model.GivePromotionList;
import com.glela.platform.model.PromotionDetail;
import com.glela.platform.model.User;
import com.glela.platform.model.UserPromotion;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.service.BaseRestrictionsService;
import com.glela.cache.redis.RedisUtil;
import com.glela.common.exception.PlatformException;
import com.glela.common.util.DateUtil;
import com.glela.common.util.StringUtil;
import com.glela.goods.mapper.DistributaryTemplateDetailsMapper;
import com.glela.goods.mapper.DistributaryTemplateMapper;
import com.glela.goods.mapper.GoodsMapper;
import com.glela.goods.mapper.GoodsNavigateMapper;

/**
* @ClassName: DistributaryServiceImpl 
* @Description: 分流入口相关业务处理
* @author NingChongQing
* @date 2018年3月15日 下午2:03:13
 */
@Service("distributaryService")
public class DistributaryServiceImpl implements DistributaryService {
	
	@Autowired
	private DistributaryTemplateMapper distributaryTemplateMapper;
	@Autowired
	private DistributaryTemplateDetailsMapper distributaryTemplateDetailMapper;
	@Autowired
	private PromotionDetailMapper promotionDetailMapper;
	@Autowired
	private UserPromotionMapper userPromotionMapper;
	@Autowired
	private BaseRestrictionsService baseRestrictionsService;
	@Autowired
	private GivePromotionListMapper givePromotionListMapper;
	@Autowired
	private GivePromotionHistoryMapper givePromotionHistoryMapper;
	@Autowired
	private RedisUtil redisUtil;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private GoodsService goodsService;
	@Autowired
	private GoodsMapper goodsMapper;
	@Autowired
	private InventoryService inventoryService;
	@Autowired
	private GoodsNavigateMapper goodsNavigateMapper;
	
	/**
	 * 获取可用模板信息
	 */
	@Override
	public List<DistributaryTemplate> achieveAvailableTemplate() {
		return this.distributaryTemplateMapper.achieveAvailableTemplate();
	}
	
	/**
	 * 获取模板内容明细
	 */
	@Override
	public List<DistributaryTemplateDetails> achieveAvailableTemplateDetails(int templateId) {
		return this.distributaryTemplateDetailMapper.achieveAvailableTemplateDetails(templateId);
	}
	
	/**
	 * 领取优惠券
	 */
	@Override
	public ResponseEntity<ResponseBaseModel> addPromotionByPromotionId(int userId, int promotionId) {
		String key = "temp:recive_promotion:" + userId + "-" + promotionId;
		String redisCache = this.redisUtil.get(key);
		if (StringUtil.isEmpty(redisCache)) {// redis没有缓存
			redisUtil.setex(key, 60, "当前" + userId + "正在领取礼包[" + promotionId +"].");
		} else {// redis有缓存，说明当前正在领取礼包，并发了，提示领取成功
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C100004), HttpStatus.OK);
		}
		List<UserPromotion> upList = this.userPromotionMapper.selectUserPromotionByPromotionIdAndUserId(promotionId, Long.valueOf(userId));
		if (CollectionUtils.isEmpty(upList)) {
			
		} else {
			// 校验数据库，已领取时删除缓存
			this.redisUtil.del(key);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C100004), HttpStatus.OK);
		}
		List<PromotionDetail> listPromotionDetail = this.promotionDetailMapper.selectPromotionDetailByPromotionId(promotionId);
		for (PromotionDetail promotionDetail : listPromotionDetail) {
			// 赠送多张优惠，存到用户优惠券时，需要拆开后在保存
			for(int i = 0 ; i < promotionDetail.getPromotionDetailNumber() ; i++){
				UserPromotion userPromotion = new UserPromotion();
				userPromotion.setPromotionId(promotionDetail.getPromotionId());
				userPromotion.setPromotionDetailId(promotionDetail.getId());
				userPromotion.setType(promotionDetail.getType());
				userPromotion.setPromotionDetailName(promotionDetail.getPromotionDetailName());
				userPromotion.setUserId(userId);
				userPromotion.setBrandId(promotionDetail.getBrandId());
				userPromotion.setGoodId(promotionDetail.getGoodId());
				userPromotion.setLimited(promotionDetail.getLimited());
				userPromotion.setIsDiscount(promotionDetail.getIsDiscount());
				userPromotion.setAmount(promotionDetail.getAmount());
				if (promotionDetail.getLimitDay() == 0) {// 没有配置限制过期时间
					userPromotion.setEffectiveTime(promotionDetail.getEffectiveTime());
					userPromotion.setExpirationTime(promotionDetail.getExpirationTime());
				} else {// 设置了N天后过期
					String nowTime = DateUtil.getNow();// 当前时间
					// 当前时间大于等于失效时间
					if (DateUtil.parse(nowTime).getTime() >= DateUtil.parse(promotionDetail.getExpirationTime()).getTime()) {
						userPromotion.setEffectiveTime(promotionDetail.getEffectiveTime());
						userPromotion.setExpirationTime(promotionDetail.getExpirationTime());
					} else if (DateUtil.parse(nowTime).getTime() >= DateUtil.parse(promotionDetail.getEffectiveTime()).getTime()) {// 当前时间大于等于生效时间
						userPromotion.setEffectiveTime(nowTime);
						// 当前时间N天后的时间（失效时间）
						String afterNowNDaysTime = DateUtil.getFewDays(promotionDetail.getLimitDay());
						// 将失效时间改成当天时间23点59分59秒
						afterNowNDaysTime = DateUtil.toDateStr(DateUtil.parse(afterNowNDaysTime)) + " 23:59:59";
						// 当前N天后的时间大于等于失效时间
						if (DateUtil.parse(afterNowNDaysTime).getTime() >= DateUtil.parse(promotionDetail.getExpirationTime()).getTime()) {
							userPromotion.setExpirationTime(promotionDetail.getExpirationTime());
						} else {// 当前N天后的时间小于失效时间
							userPromotion.setExpirationTime(afterNowNDaysTime);
						}
					} else {// 当前时间小于优惠券生效时间
						userPromotion.setEffectiveTime(promotionDetail.getEffectiveTime());
						// 生效时间N天后的日期（失效时间）
						String afterEffectiveTimeNDaysTime = DateUtil.getFewDays(DateUtil.parse(promotionDetail.getEffectiveTime()),promotionDetail.getLimitDay());
						// 将失效时间改成当天时间23点59分59秒
						afterEffectiveTimeNDaysTime = DateUtil.toDateStr(DateUtil.parse(afterEffectiveTimeNDaysTime)) + " 23:59:59";
						// 失效时间大于等于生效时间N天后的时间
						if (DateUtil.parse(promotionDetail.getExpirationTime()).getTime() >= DateUtil.parse(afterEffectiveTimeNDaysTime).getTime()) {
							userPromotion.setExpirationTime(afterEffectiveTimeNDaysTime);
						} else {// 失效时间小于生效时间N天后的时间
							userPromotion.setExpirationTime(promotionDetail.getExpirationTime());
						}
					}
				}
				userPromotion.setPromotionNumber(1);
				userPromotion.setTargetSelfType(promotionDetail.getTargetSelfType());
				userPromotion.setDiscount(promotionDetail.getDiscount());
				this.userPromotionMapper.insertUserPromotion(userPromotion);
			}
		}
		// 优惠券过期时间
		Integer expirationDay = this.baseRestrictionsService.getBaseRestrictionsForCache("expiration_day").getExperience();
		User user = this.userMapper.selectByPrimaryKey(Long.valueOf(userId));
		String jobNo = "80012";
		Date nowDate = DateUtil.toDate(System.currentTimeMillis());
		GivePromotionList givePromotionList = new GivePromotionList();
		givePromotionList.setTearchUserId(6497);
		givePromotionList.setTearchJobNo(jobNo);
		givePromotionList.setGiveTime(nowDate);
		givePromotionList.setPromotionId(promotionId);
		givePromotionList.setAdminUserId(0);
		givePromotionList.setNums(1);
		this.givePromotionListMapper.insertAndGetId(givePromotionList);
		GivePromotionHistory gph = new GivePromotionHistory();
		gph.setTearchUserId(6497L);
		gph.setTearchJobNo(jobNo);
		gph.setAdminUserId(0L);
		gph.setUserId(Long.valueOf(userId));
		gph.setUserRoleId(Long.valueOf(user.getRoleId()));
		gph.setPromotionId(Long.valueOf(promotionId));
		gph.setGiveTime(nowDate);
		gph.setGetTime(nowDate);
		gph.setExpirationTime(DateUtil.parse(DateUtil.getFewDays(expirationDay)));
		gph.setStatus(0);// 已领取
		gph.setpId(givePromotionList.getId());
		this.givePromotionHistoryMapper.insertSelective(gph);
		redisCache = this.redisUtil.get(key);
		if (StringUtil.isEmpty(redisCache)) {// redis没有缓存 说明被其他请求给消费了
			throw new PlatformException("已领取");
		} else {
			// 礼包领取完毕后，删除Redis缓存，不然下次提交请求会被拒绝
			this.redisUtil.del(key);
		}
		return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C10000), HttpStatus.OK);
	}
	
	
	/**
	 * 临时商品列表
	 */
	@Override
	public List<GoodsListResponse> achieveTempGoodsInfo(String tempGoodsIdsStr,Long storeUserId) {
		List<GoodsListResponse> listGoodsListResponse = new ArrayList<GoodsListResponse>();
		List<Long> goodsIds = new ArrayList<Long>();
		String[] goodsIdArray = tempGoodsIdsStr.split(",");
		for(int i =0 ;i < goodsIdArray.length;i++){
			goodsIds.add(Long.valueOf(goodsIdArray[i]));
		}
		User user = this.userMapper.selectByPrimaryKey(storeUserId);
		Map<Long,GoodsPrice> goodsPriceMap = this.goodsService.getGoodsViewPriceForGoods(user, goodsIds);
		Map<Long,Long> inventoryMap = this.inventoryService.findDynaByGoodsId(goodsIds);
		for(int i =0 ; i < goodsIdArray.length ; i++){
			try {
				Goods goods	= this.goodsMapper.selectGoodsByIdForAll(Long.valueOf(goodsIdArray[i]));
				GoodsListResponse goodsListResponse = new GoodsListResponse();
				goodsListResponse.setGoodId(goods.getId());
				goodsListResponse.setLabelName(goods.getLabelName());
				goodsListResponse.setGoodsName(goods.getName());
				goodsListResponse.setName(goods.getName());
				goodsListResponse.setTitle(goods.getTitle());
				goodsListResponse.setSuggestedPrice(goods.getSuggestedPrice());
				List<GoodsNavigate> goodsNavigateList = this.goodsNavigateMapper.selectGoodsNavigateByGoodId(goods.getId());
				String goodNavigateImage = "";
				if (!CollectionUtils.isEmpty(goodsNavigateList)) {
					goodNavigateImage = goodsNavigateList.get(0).getNavigateImage();
				}
				goodsListResponse.setGoodNavigateImage(goodNavigateImage);
				goodsListResponse.setBrandName("");
				goodsListResponse.setSelfSupport(goods.getSelfSupport());
				GoodsPrice goodsPrice = goodsPriceMap.get(goods.getId())==null?this.goodsService.getGoodsViewPriceForGoods(user, goods.getId()):goodsPriceMap.get(goods.getId());
				String nowTime = DateUtil.currentStringDate();
				//商品标签
				List<Map<String,String>> labelArray = new ArrayList<Map<String,String>>();
				// 状态（SecKill:秒杀中;NormalSale:原价销售;PreHeat:预热中;UnderCarriage:下架了）
				// 原价销售：没有参与分时抢购活动，且未被下架。--默认	
				// 预热中：分时抢购活动，且服务器当前时间小于秒杀活动开始时间；	 
				// 秒杀中：分时抢购活动，且服务器当前时间大于秒杀活动开始时间，小于秒杀活动结束时间；	
				// 抢光：分时抢购活动，且APP实际库存与分时抢购活动设置的库存中的最小的一个数量小于等于0；	
				// 下架：商品下架时间小于服务器当前时间或者下架时间字段为空值；	
				String saleStatus = "NormalSale";// 默认原价销售状态
				//存在goodsPrice对象为null的情况
				if (goodsPrice!=null) {
					Long productId = goodsPrice.getProductId();
					// 查询是否存在分时抢购活动
					Map<String,Object> ltsMap = this.goodsMapper.selectNearlyLimitTimeSale(goods.getId(),productId,nowTime);
					if(ltsMap != null){
						Map<String,String> tmLabel = new HashMap<String, String>();
						// 分时抢购开始时间
						try {
							SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
							Date fullBeginTime = sdf.parse(ltsMap.get("fullBeginTime").toString());
							// 系统当前时间
							long nowTimeMillis = System.currentTimeMillis();
							if (fullBeginTime.getTime() > nowTimeMillis) {// 预热中
								saleStatus = "PreHeat";
								tmLabel.put("label", "预热");
							} else {// 抢购中
								saleStatus = "SecKill";
								tmLabel.put("label", "特卖");
							}
						} catch (ParseException e) {
							
						}
						tmLabel.put("color", "#ff4b7a");
						labelArray.add(tmLabel);
					}
				}
				// 实时库存
				long realTimeInventory = inventoryMap.get(goods.getId())==null?0:inventoryMap.get(goods.getId());//this.inventoryService.findDynaByGoodsId(goods.getId()):inventoryMap.get(goods.getId());
				// 下架了
				if(goods.getOnlineTime() == null || 
						goods.getOfflineTime() == null || 
						(DateUtil.betweenTime(goods.getOnlineTime(), goods.getOfflineTime()) < 1)){
					saleStatus = "UnderCarriage";
				}
				// C区商品  设置为已下架状态
				if(goods.getGoodsType() == 0){
					saleStatus = "UnderCarriage";
				}
				goodsListResponse.setSaleStatus(saleStatus);// 销售状态
				goodsListResponse.setGoodsPrice(goodsPrice);// 价格信息
				goodsListResponse.setInventoryNum(realTimeInventory);// 库存数
				goodsListResponse.setSalerNums(goods.getUpCount());
				goodsListResponse.setLabelArray(labelArray);// 标签信息
				listGoodsListResponse.add(goodsListResponse);
			} catch (Exception e) {
				continue;
			}
		}
		return listGoodsListResponse;
	}
}
